﻿CREATE function [dbo].[fn_GetBusinessDays]
(
@StartDate datetime,
@EndDate datetime
)
returns int as
begin
declare @AdjStart datetime,@IntDays int, @Inverse bit

IF( @StartDate>@EndDate)BEGIN
DECLARE @D datetime SELECT @D = @EndDate, @EndDate = @StartDate,@StartDate = @D,@Inverse = 1
END

Select @AdjStart = dateadd(dd, (floor(DateDiff(dd, @StartDate, @EndDate)/7)*7), @StartDate)
Select @IntDays = (
floor(DateDiff(dd, @StartDate, @EndDate)/7)*5) + (datediff(dd, @AdjStart, @EndDate) - 2 +
case when datepart(dw, @AdjStart) < abs(-8 + datediff(dd, @AdjStart, @EndDate)) + 1 
then 1 else 0 end +
case when datepart(dw, @AdjStart) > 1 and datepart(dw, @AdjStart) < abs(-8 + datediff(dd, @AdjStart, @EndDate))
then 1 else 0 end
)

/*
--Use this to deincrement for holidays if necessary
select @intDays = @intDays 
case when '01/01/2001' between @startdate and @enddate and datepart(dw, '01/01/2001') between 2 and 6 then 1 else 0 end 
case when '07/04/2001' between @startdate and @enddate and datepart(dw, '07/04/2001') between 2 and 6 then 1 else 0 end 
--minus additional days in the calendar year by listing each 
*/
return CASE @Inverse WHEN 1 THEN -@intDays ELSE @intDays END
end

